import fs from 'node:fs'
import fpath from 'node:path'

import { astToJSON5 as $astToJSON5, parseComment as $parseComment, obj2ast } from './obj-ast'

interface IConfig {
  sources: {
    files: string
  }[]
}
export const parseComment = $parseComment
export const astToJSON5 = $astToJSON5

export async function parseConfig(options: IConfig) {
  const sources = options.sources
  const filePath = sources.map(e => getFilePath(e.files))

  try {
    const res: string[] = (await Promise.all(filePath.map(e => readFile(e))))
    const result = []
    for (let i = 0; i < res.length; i++) {
      const fileStr = res[i]
      const { ast, json } = obj2ast(fileStr)
      if (json) {
        result.push({
          path: filePath[i],
          config: json,
          ast,
          rawConfig: fileStr
        })
      }
      else {
        console.log(`未解析到配置,路径-->${filePath[i]}`)
      }
    }
    return result
  }
  catch (error) {
    return []
  }
}
function getFilePath(filePath: string) {
  if (/\.(ts|js|json|json5|jsonc)$/.test(filePath)) {
    return filePath
  }
  const dir = fpath.dirname(filePath)
  const base = fpath.basename(filePath)
  const files = fs.readdirSync(dir)
  return fpath.join(dir, files.find(e => e.endsWith(`${base}.ts`) || e.endsWith(`${base}.js`) || e.endsWith(`${base}.json`) || e.endsWith(`${base}.json5`) || e.endsWith(`${base}.jsonc`)) || '')
}

function readFile(path: string): Promise<string> {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf-8', (err, data) => {
      if (err) {
        reject(err)
      }
      else {
        resolve(data)
      }
    })
  })
}
